<template>
  <div>
    <div class="send__search">
      <div>
        <el-form ref="form" :model="lQuery" label-width="80px">
          <el-form-item label="发货方式" required>
            <el-radio-group v-model="lQuery.type">
              <el-radio label="手动发货"></el-radio>
              <el-radio label="打印快递单并发货"></el-radio>
              <el-radio label="无需物流"></el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="!isNotLogistics">
            <el-form-item label="物流公司" required>
              <el-select
                style="width:250px"
                v-model="lQuery.deliverCode"
                placeholder="请选择"
              >
                <el-option
                  v-for="item of logisticsCompany"
                  :label="item.name"
                  :key="item.code"
                  :value="item.code"
                  >{{ item.name }}</el-option
                >
              </el-select>
              <el-link
                v-if="!isManual"
                type="primary"
                :underline="false"
                style="margin-left:4px"
                @click="setDefaultAddress"
                :disabled="deliverCodeBtnStatus"
                >设为默认</el-link
              >
            </el-form-item>
            <template v-if="!isManual">
              <el-form-item label="打印机" required>
                <el-select
                  style="width:250px"
                  v-model="lQuery.printCode"
                  placeholder="选择打印机"
                >
                  <el-option
                    v-for="item of logisticsPrinterVos"
                    :key="item.deviceKey"
                    :label="item.deviceName"
                    :value="item.deviceKey"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="发货地址" required>
                <el-select
                  v-model="lQuery.expressId"
                  :disabled="!logisticsAddressVos.length"
                  placeholder="选择发货地址"
                  style="width:250px"
                >
                  <el-option
                    v-for="item of logisticsAddressVos"
                    :key="item.code"
                    :label="item.address"
                    :value="item.expressId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </template>
        </el-form>
      </div>
      <div>
        <el-link type="primary" :underline="false" @click="handleImportAll"
          >导入全部待发货订单</el-link
        >
      </div>
    </div>
    <m-table
      :data="orderList"
      ref="product"
      style="margin-top:20px;width:100%"
      v-show="lQuery.type === '手动发货'"
    >
      <template v-slot:header="{ row, index }">
        <div style="width:100%">
          <span style="margin-right:50px">订单号：{{ row.prizeOrderId }}</span>
          <span style="margin-right:50px">创建时间：{{ row.createTime }}</span>
          <el-link
            type="primary"
            style="float:right"
            :underline="false"
            @click="handleRemove(index)"
            >移除</el-link
          >
        </div>
      </template>
      <m-table-column label="商品">
        <template v-slot="{ row }">
          <div class="shopName">
            <div style="width:60px;height:60px">
              <img
                :src="row.shoppingInfVos[0].pic"
                alt=""
                style="width:60px;height:60px"
              />
            </div>
            <div class="shopName__name">
              <div>{{ row.shoppingInfVos[0].integralGoodName }}</div>
              <div>{{ row.shoppingInfVos[0].integralPrice }}</div>
              <div>X1</div>
            </div>
          </div>
        </template>
      </m-table-column>
      <m-table-column label="客户">
        <template v-slot="{ row }">
          <div class="shopName" style="padding-left:120px">
            <img
              :src="row.memberAvatarUrl"
              alt=""
              style="width:60px;height:60px"
            />
            <div class="shopName__name">{{ row.wxuserName }}</div>
          </div>
        </template>
      </m-table-column>
      <m-table-column label="地址">
        <template v-slot="{ row }">
          <div class="middleCenter">
            <div style="padding-left:30px">物流配送</div>
            <div style="padding-left:30px">
              {{ row.receiverName }},{{ row.telPhone }}
            </div>
            <div style="padding-left:30px">{{ row.address }}</div>
          </div>
        </template>
      </m-table-column>
      <m-table-column label="操作" width="310px">
        <template v-slot="{ row }">
          <div class="sendDig">
            <div class="sendDig__line">
              <div style="width: 55px">*选择物流</div>
              <el-select
                v-model="row.deliveryCompany"
                placeholder="请选择物流公司"
                style="width:180px;margin-left:20px;"
                @change="changeOneComp(row)"
              >
                <el-option
                  v-for="item in logisticsCompany"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </div>
            <div class="sendDig__line">
              <div style="width: 55px">*运单号码</div>
              <el-input
                placeholder="请输入运单号码"
                v-model="row.deliverySn"
                style="width:180px;margin-left:20px;"
                @change="inputOneComp(row)"
              ></el-input>
            </div>
          </div>
        </template>
      </m-table-column>
    </m-table>
    <m-table
      :data="orderList"
      ref="product"
      style="margin-top:20px;width:100%"
      v-show="lQuery.type !== '手动发货'"
    >
      <template v-slot:header="{ row, index }">
        <div style="width:100%">
          <span style="margin-right:50px">订单号：{{ row.prizeOrderId }}</span>
          <span style="margin-right:50px">创建时间：{{ row.createTime }}</span>
          <el-link
            type="primary"
            style="float:right"
            :underline="false"
            @click="handleRemove(index)"
            >移除</el-link
          >
        </div>
      </template>
      <m-table-column label="商品">
        <template v-slot="{ row }">
          <div class="shopName">
            <div style="width:60px;height:60px">
              <img
                :src="row.shoppingInfVos[0].pic"
                alt=""
                style="width:60px;height:60px"
              />
            </div>
            <div class="shopName__name">
              <div>{{ row.shoppingInfVos[0].integralGoodName }}</div>
              <div>{{ row.shoppingInfVos[0].integralPrice }}</div>
              <div>X1</div>
            </div>
          </div>
        </template>
      </m-table-column>
      <m-table-column label="客户">
        <template v-slot="{ row }">
          <div class="shopName" style="padding-left: 120px;">
            <img
              :src="row.memberAvatarUrl"
              alt=""
              style="width:60px;height:60px;"
            />
            <div class="shopName__name">{{ row.wxuserName }}</div>
          </div>
        </template>
      </m-table-column>
      <m-table-column label="地址">
        <template v-slot="{ row }">
          <div class="middleCenter">
            <div style="padding-left:120px">物流配送</div>
            <div style="padding-left:120px">
              {{ row.receiverName }},{{ row.telPhone }}
            </div>
            <div style="padding-left:120px">{{ row.address }}</div>
          </div>
        </template>
      </m-table-column>
    </m-table>
    <div class="next">
      <el-button @click="back">取消</el-button>
      <el-button type="primary" @click="sendSome">发货</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch, Ref } from "vue-property-decorator";
import DeliverSelectComp from "./components/DeliverSelectComp.vue";
import {
  setDefaultAddress,
  getLogisticsCompany,
  importAllOrder,
  sendNoLogistic,
} from "@/api/logistics/logistics";
import {
  sendOneintegralGood,
  sendintegralGoodByPrint,
} from "@/api/integral/integral";

@Component({
  components: {
    DeliverSelectComp,
  },
})
export default class DeliverGoods extends Vue {
  get isManual() {
    return this.lQuery.type === "手动发货";
  }

  /**
   * 是否为无需物流发货
   */
  get isNotLogistics() {
    return this.lQuery.type === "无需物流";
  }

  lQuery = {
    type: "手动发货",
    printCode: "",
    deliverCode: "",
    expressId: "",
  };

  /**
   * 打印机
   */
  logisticsPrinterVos = [];

  /** 设置默认按钮状态 */
  get deliverCodeBtnStatus() {
    return (
      !this.lQuery.deliverCode ||
      (this.defLogisticsCompany &&
        this.defLogisticsCompany.code === this.lQuery.deliverCode)
    );
  }

  get logisticsAddressVos() {
    try {
      const { logisticsExpressAddressVos } = this.logisticsCompany.find(
        item => item.code === this.lQuery.deliverCode,
      );
      return logisticsExpressAddressVos;
    } catch (err) {
      return [];
    }
  }

  /** 默认物流公司 */
  get defLogisticsCompany() {
    return this.logisticsCompany.find(item => item.isDefault === 1) || {};
  }

  /** 物流公司 */
  logisticsCompany = [] as any;

  /** 待发货订单 */
  orderList = [];

  @Watch("lQuery.deliverCode")
  handleCompanyChage(v) {
    this.orderList = this.orderList.map(item => {
      item.deliveryCompany = v;
      return item;
    });
  }

  @Ref()
  readonly deliver: HTMLFormElement;

  mounted() {
    if (this.$route.params.orderList) {
      this.orderList = JSON.parse(JSON.stringify(this.$route.params.orderList));
    }
    this.getLogisticsCompany();
  }

  /**
   * 获取物流公司与打印机
   */
  getLogisticsCompany() {
    getLogisticsCompany({})
      .then(res => {
        this.logisticsCompany = res.data.logisticsCompanyVos;
        this.logisticsPrinterVos = res.data.LogisticsPrinterVos;
        this.logisticsCompany.forEach(item => {
          if (item.isDefault === 1) {
            this.lQuery.deliverCode = item.code;
            item.name = item.name + "(默认)";
          }
        });
      })
      .catch(err => {
        this.$message.warning(err);
      });
  }

  /** 设置默认发货公司 */
  setDefaultAddress() {
    const { logisticsCompanyId } = this.logisticsCompany.find(
      item => item.code === this.lQuery.deliverCode,
    );
    setDefaultAddress(logisticsCompanyId)
      .then(() => {
        this.getLogisticsCompany();
        this.$message.success("设置成功");
      })
      .catch(err => {
        this.$message.warning(err);
      });
  }

  /**
   * 导入所有待发货订单
   */
  handleImportAll() {
    importAllOrder({}).then(res => {
      this.orderList = res.data;
      this.orderList.forEach(item => {
        item.deliveryCompany = this.defLogisticsCompany.code;
      });
    });
  }

  /**
   * 移除订单
   */
  handleRemove(index) {
    this.orderList.splice(index, 1);
  }

  /**
   * 选择单个物流公司
   */
  changeOneComp(row) {
    this.logisticsCompany.forEach(item => {
      if (item.prizeOrderId === row.prizeOrderId) {
        item.deliveComp = row.deliveComp;
      }
    });
  }

  /**
   * 输入单个运单号码
   */
  inputOneComp(row) {
    this.orderList.forEach(item => {
      if (item.prizeOrderId === row.prizeOrderId) {
        item.deliverySn = row.deliverySn;
      }
    });
  }

  /**
   * 批量发货
   */
  sendSome() {
    if (this.lQuery.type === "打印快递单并发货") {
      this.sendByPrint();
      return;
    }
    if (this.lQuery.type === "无需物流") {
      this.sendNo();
      return;
    }
    const type = this.orderList.every(item => {
      return item.deliveryCompany !== null && !item.deliverySn !== null;
    });
    if (!type) {
      this.$message.error("请填写物流信息");
      return;
    }
    this.orderList.forEach(item => {
      delete item.createTime;
    });
    sendOneintegralGood(this.orderList)
      .then(() => {
        this.$message.success("发货成功");
        this.isBack();
      })
      .catch(err => {
        this.$message.error(err || "网络错误");
      });
  }

  /**
   * 打印发货
   */
  sendByPrint() {
    if (
      !this.lQuery.deliverCode ||
      !this.lQuery.printCode ||
      !this.lQuery.expressId
    ) {
      this.$message.error("请填写打印信息");
      return;
    }
    const logisticsPrintDeliverDto = {
      orderIds: [],
      ...this.lQuery,
      isIntegralOrder: -1,
    } as any;
    this.orderList.forEach(item => {
      logisticsPrintDeliverDto.orderIds.push(item.prizeOrderId);
    });
    sendintegralGoodByPrint(logisticsPrintDeliverDto)
      .then(() => {
        this.$message.success("发货成功");
        this.isBack();
      })
      .catch(err => {
        this.$message.error(err || "网络错误");
      });
  }

  /**
   * 无需物流发货
   */
  sendNo() {
    const integralOrders = [];
    this.orderList.forEach(item => {
      integralOrders.push(item.prizeOrderId);
    });
    sendNoLogistic(integralOrders)
      .then(() => {
        this.$message.success("发货成功");
        this.isBack();
      })
      .catch(err => {
        this.$message.error(err || "网络错误");
      });
  }

  isBack() {
    this.$router.push({
      name: "integralMallIndex",
      params: { type: "deliver" },
    });
  }

  /**
   * 取消发货
   */
  back() {
    this.$confirm("你确定要退出批量发货页面?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      this.$router.push({
        name: "integralMallIndex",
        params: { type: "deliver" },
      });
    });
  }
}
</script>

<style lang="scss" scoped>
@include b(send) {
  padding-bottom: 50px;
  min-height: 720px;
  padding: 10px 15px 100px;

  \deep\  .el-input-group__prepend .el-select {
    min-width: 100px;
  }

  \deep\ .el-pagination__sizes {
    position: relative !important;
    top: -5px !important;
  }

  @include e(search) {
    @include flex(space-between);
  }

  @include e(form) {
    .el-form-item {
      margin: 5px 0;
    }
  }

  .send__bottom {
    @include flex();

    width: 1010px;
    padding: 15px 0px;
    box-shadow: 0 0px 10px 0px #d5d5d5;
    position: fixed;
    // bottom: -20px;
    // left: -15px;
    z-index: 9;
    bottom: 10px;
    background: #fff;
  }
}

.shopName {
  display: flex;
  justify-content: center;
  align-items: center;

  &__name {
    width: 110px;
    margin-left: 20px;
    padding-top: 10px;
  }
}

.middleCenter {
  //   @include flex(center, center);
  flex-direction: column;
}

.upDown {
  display: flex;
  align-items: center;
  justify-content: center;
  &--goodUp {
    display: flex;
    width: 40px;
    height: 20px;
    justify-content: center;
    align-items: center;
    border-radius: 4px;
    color: white;
    margin-right: 10px;
  }
  &--goodDown {
    margin-left: 10px;
    color: #2d8cf0;
    cursor: pointer;
  }
}

@include b(sendDig) {
  padding: 20px;
  @include e(line) {
    width: 100%;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
  }
}

.next {
  padding-top: 20px;
  height: 80px;
  @include flex(center, center);
  box-shadow: 0 0px 10px 0px #d5d5d5;
}
</style>
